<?php
@session_start();
/*
 * Debug function for array
 * @author	:chientran@vietnambiz.com
 * @created	:17/05/2012
 * @param 	:array
 * @return 	:output
 */

function _debug($arr) {
	echo "<pre>";
	print_r($arr);
	echo "</pre>";
}

function _debug2($arr) {
	echo "<pre>";
	var_dump($arr);
	echo "</pre>";
}

function url_friendly($title){
    $title = trim($title);
    $strFind = array(
            ': ',':',
            ' ',
            'đ','Đ',
            'á','à','ạ','ả','ã','Á','À','Ạ','Ả','Ã','ă','ắ','ằ','ặ','ẳ','ẵ','Ă','Ắ','Ằ','Ặ','Ẳ','Ẵ','â','ấ','ầ','ậ','ẩ','ẫ','Â','Ấ','Ầ','Ậ','Ẩ','Ẫ',
            'ó','ò','ọ','ỏ','õ','Ó','Ò','Ọ','Ỏ','Õ','ô','ố','ồ','ộ','ổ','ỗ','Ô','Ố','Ồ','Ộ','Ổ','Ỗ','ơ','ớ','ờ','ợ','ở','ỡ','Ơ','Ớ','Ờ','Ợ','Ở','Ỡ',
            'é','è','ẹ','ẻ','ẽ','É','È','Ẹ','Ẻ','Ẽ','ê','ế','ề','ệ','ể','ễ','Ê','Ế','Ề','Ệ','Ể','Ễ',
            'ú','ù','ụ','ủ','ũ','Ú','Ù','Ụ','Ủ','Ũ','ư','ứ','ừ','ự','ử','ữ','Ư','Ứ','Ừ','Ự','Ử','Ữ',
            'í','ì','ị','ỉ','ĩ','Í','Ì','Ị','Ỉ','Ĩ',
            'ý','ỳ','ỵ','ỷ','ỹ','Ý','Ỳ','Ỵ','Ỷ','Ỹ'
    );
    $strReplace = array(
            '-', '-',
            '-',
            'd','d',
            'a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a',
            'o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o',
            'e','e','e','e','e','e','e','e','e','e','e','e','e','e','e','e','e','e','e','e','e','e',
            'u','u','u','u','u','u','u','u','u','u','u','u','u','u','u','u','u','u','u','u','u','u',
            'i','i','i','i','i','i','i','i','i','i',
            'y','y','y','y','y','y','y','y','y','y'
    );

    return strtolower(preg_replace( '/[^a-z0-9\-]+/i','', str_replace($strFind, $strReplace, $title) ) );
}

function convertDateToTime($str) {
    list($day, $month, $year) = explode('/', $str);
    $time = mktime(0, 0, 0, $month, $day, $year);
    return $time;
}

function convertTimeToDate($time){
    return date('d/m/Y',$time);

}

function firstOfMonth($month = NULL) {
    if(is_null($month)):
        return strtotime(date('m') . '/01/' . date('Y') . ' 00:00:00');
    else:
        return strtotime($month . '/01/' . date('Y') . ' 00:00:00');
    endif;

}

function lastOfMonth($month = NULL) {
    if(is_null($month)):
        return strtotime('-1 second', strtotime('+1 month', strtotime(date('m') . '/01/' . date('Y') . ' 00:00:00')));
    else:
        return strtotime('-1 second', strtotime('+1 month', strtotime($month . '/01/' . date('Y') . ' 00:00:00')));
    endif;

}

function createFolder($username, $type = 'avatar', $path = 'images/user/') {
    if ($type == 'avatar'):
        if (!is_dir($path)):
            mkdir($path);
        endif;

        $path = $path . $username;
        if (!is_dir($path)):
            mkdir($path);
        endif;

        $path = $path . '/avatar/';
        if (!is_dir($path)):
            mkdir($path);
        endif;
    endif;
    return $path;
}

function removeFolder($username, $type = 'avatar', $path = 'images/user/') {
    $path1 = $path . $username . '/avatar/';
    if ($type == 'avatar'):
        if (is_dir($path1)):
            rmdir($path1);
        endif;
        $path2 = $path . $username;
        if (is_dir($path2)):
            rmdir($path2);
        endif;
    endif;
    return $path;
}

function getExtension($str) {
    $i = strrpos($str, ".");
    if (!$i) {
        return "";
    }
    $l = strlen($str) - $i;
    $ext = substr($str, $i + 1, $l);
    return $ext;
}

function upload($input_name, $dir = 'images/', $width_img = 100) {

    $errors = 0;
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $image = $_FILES[$input_name]["name"];
        $uploadedfile = $_FILES[$input_name]['tmp_name'];

        if ($image) {
            $filename = stripslashes($_FILES[$input_name]['name']);
            $extension = getExtension($filename);
            $extension = strtolower($extension);
            if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
                $change = 'Xin mời chọn file ảnh !';
                $errors = 1;
            } else {

                $size = filesize($_FILES[$input_name]['tmp_name']);

                if ($size > MAX_SIZE * 1024) {
                    $change = 'Kích thước vượt quá giới hạn cho phép !';
                    $errors = 1;
                }
                if ($extension == "jpg" || $extension == "jpeg") {
                    $uploadedfile = $_FILES[$input_name]['tmp_name'];
                    $src = imagecreatefromjpeg($uploadedfile);
                } else if ($extension == "png") {
                    $uploadedfile = $_FILES[$input_name]['tmp_name'];
                    $src = imagecreatefrompng($uploadedfile);
                } else {
                    $src = imagecreatefromgif($uploadedfile);
                }
                list($width, $height) = getimagesize($uploadedfile);
                $newheight1 = ($height / $width) * $width_img;
                $tmp1 = imagecreatetruecolor($width_img, $newheight1);
                imagecopyresampled($tmp1, $src, 0, 0, 0, 0, $width_img, $newheight1, $width, $height);
                $filename = $dir . $_FILES[$input_name]['name'];
                $filename1 = $dir . $_FILES[$input_name]['name'];
                @imagejpeg($tmp1, $filename1, 100);
                @imagedestroy($src);
                @imagedestroy($tmp1);

                @move_uploaded_file($uploadedfile, $dir . $filename);
            }
        }
    }

    if ($errors == 1):
        return $change;
    else:
        return '1';
    endif;
}

/**
 * Calculate memory using for image resize
 * @param string $filename
 * @return boolean
 */
function setMemoryForImage( $filename ){
    $imageInfo = getimagesize($filename);
    $memoryLimitMB = 0;
    $MB = 1048576;  // number of bytes in 1M
    $K64 = 65536;    // number of bytes in 64K
    $TWEAKFACTOR = 8;  // Or whatever works for you
    $memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
            * $imageInfo['bits']
            * $imageInfo['channels'] / 8
            + $K64
    ) * $TWEAKFACTOR
    );
    //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
    //Default memory limit is 8MB so well stick with that.
    //To find out what yours is, view your php.ini file.
    $memoryLimit = 8 * $MB;
    if (function_exists('memory_get_usage') &&
            memory_get_usage() + $memoryNeeded > $memoryLimit)
    {
        $newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
                + $memoryNeeded
                - $memoryLimit
        ) / $MB
        );
        ini_set( 'memory_limit', $newLimit . 'M' );
        return true;
    }
    else{
        return false;
    }
}

function get_block($block = ''){
    $CI = get_instance();
    $CI->load->view($block);
}

function get_manufacturer(){
    $ci = get_instance();
    $ci->load->model('product/product_model');
    #$product_model = new Product_model();
    $data['result'] = $ci->product_model->get_manufacturer();
    $ci->load->view('product/manufacturer', $data);
}

function get_cart(){
    $CI = get_instance();
    $CI->load->model('cart/cart_model');
    #$cart_model = new Cart_model();
    $data['result'] = $CI->cart_model->chien();
    $CI->load->view('cart/block', $data);
}

function product_status($type = NULL){
    $product_status = array(
        0 => 'Old',
        1 => 'New'
    );

    if (!is_null($type)){
        return $product_status[$type];
    }
    return $product_status;
}

function webgame_type($type = NULL){
    $value = array(
        0 => '--- Webgame ---',
        1 => 'SIM',
        2 => 'RPG',
        3 => 'SLG'
    );

    if (!is_null($type)){
        return $value[$type];
    }
    return $value;
}

function currency_format($number){
    return number_format($number, 0);
}

function field($table = '', $field = '', $where = ''){
    $query = 'SELECT '.$field.' FROM '.$table;
    if ($where != ''){
        $query .= ' WHERE '.$where;
    }

    $CI = get_instance();
    return $CI->db->query($query)->row_array();
}

/*
 * Recursively copy a directory
 */
function copy_dir( $source, $destination ) {
    if ( is_dir( $source ) ) {
        umask(0);
        @mkdir( $destination, 0777, 1);
        $directory = dir( $source );
        while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
            if ( $readdirectory == '.' || $readdirectory == '..' ) {
                continue;
            }
            $PathDir = $source . '/' . $readdirectory;
            if ( is_dir( $PathDir ) ) {
                copy_dir( $PathDir, $destination . '/' . $readdirectory );
                continue;
            }
            copy( $PathDir, $destination . '/' . $readdirectory );
        }

        $directory->close();
    }else {
        copy( $source, $destination );
    }
}

/*
 * Recursively remove a directory
 */
function remove_dir($dir) {
    foreach(glob($dir . '/*') as $file) {
        if(is_dir($file))
            remove_dir($file);
        else
            unlink($file);
    }
    rmdir($dir);
}

/**
 * Get random string
 *
 * @return string
 * @author chientran@vietnambiz.com
 */
function genRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

function only_numeric($string){
    return preg_replace('/[^\d]/', '', $string);
}

function render_image($url = '', $width = 150, $height = 150, $crop = '1.1'){
    return base_url('images/w'.$width.'-h'.$height.'-c'.$crop.'/'.$url);
}

function _c(){
    $ci = get_instance();
    $ci->output->enable_profiler(true);
}

function cut_string($str, $len)
{
    $return_str = '';
    $arrChar = array();
    preg_match_all('/./u', $str, $arrChar);
    $k = 1;
    foreach ($arrChar[0] as $v) {
        if ($k < $len) {
            $return_str .= $v;
        } elseif ($len == $k && $v == ' ') {
            $return_str .= '...';
            break;
        } else {
            if ($v === ' ') {
                $return_str .= '...';
                break;
            } else {
                $return_str .= $v;
            }
        }
        $k++;
    }
    return $return_str;
}

function get_curl($url){
	if($url):
		$file = $url;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $file);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	else:
		return '';
	endif;
}

function news_category_block(){
    $ci = get_instance();
    $data['news_category_block'] = $ci->db->order_by('title asc')
                                  ->get(TBL_NEWS_CATEGORY)
                                  ->result();
    $ci->load->view('news/block_category', $data);
}

function page_type($type = null){
    $value = array(
        0    => '-- Loại trạng ---',
        1    => 'Giới thiệu',
        2    => 'Giải pháp',
        3    => 'Tuyển dụng',
        4    => 'Liên hệ'
    );

    if (!is_null($type)){
        return $value[$type];
    }
    return $value;
}

function slider_type($type = null){
    $value = array(
        0    => '-- Loại trạng ---',
        1    => 'Trang chủ'
    );

    if (!is_null($type)){
        return $value[$type];
    }
    return $value;
}

function block_news($limit = 5){
    $ci = get_instance();
    $ci->db->from(TBL_NEWS);
    $ci->db->where('active_flag', ACTIVE_FLAG);
    $ci->db->where('delete_flag', UNDELETE_FLAG);
    $ci->db->where('draft', DRAFT_NO);
    $ci->db->limit($limit);
    $ci->db->order_by('create_date desc');
    $data['news_newest'] = $ci->db->get()->result();
    $data['tpl'] = 'news/block_newest';
    $ci->load->view('_layout/single', $data);
}

function block_slider($limit = 5){
	$ci = get_instance();
    $ci->db->from(TBL_SLIDER);
    $ci->db->where('active_flag', ACTIVE_FLAG);
    $ci->db->where('delete_flag', UNDELETE_FLAG);
    $ci->db->where('draft', DRAFT_NO);
    $ci->db->limit($limit);
    $ci->db->order_by('create_date desc');
    $data['slider'] = $ci->db->get()->result();
    $ci->load->view('_layout/block_slider', $data);
}

function block_pages($limit = 5, $type = 0){
    $type= intval($type);
    $ci = get_instance();
    if ($type != 0){
        $ci->db->where('type', $type);
    }
    $ci->db->from(TBL_PAGES);
    $ci->db->where('active_flag', ACTIVE_FLAG);
    $ci->db->where('delete_flag', UNDELETE_FLAG);
    $ci->db->where('draft', DRAFT_NO);
    $ci->db->limit($limit);
    $ci->db->order_by('create_date desc');
    $data['pages_newest'] = $ci->db->get()->result();
    $data['tpl'] = 'pages/block_newest';
    $ci->load->view('_layout/single', $data);
}